package com.feeyo.groundservice.checkin.dlg

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ScreenUtils
import com.feeyo.groundservice.base_util.SuccessCallback
import com.feeyo.groundservice.base_util.dealString
import com.feeyo.groundservice.base_util.formatTimeHMWithDay
import com.feeyo.groundservice.base_util.getConfirmDlg
import com.feeyo.groundservice.base_util.toastCenter
import com.feeyo.groundservice.checkin.R
import com.feeyo.groundservice.checkin.constant.checkInListRefreshFlag
import com.feeyo.groundservice.checkin.constant.openDetailData
import com.feeyo.groundservice.checkin.constant.showAddCheckInPop
import com.feeyo.groundservice.checkin.constant.statusBarColor
import com.feeyo.groundservice.checkin.databinding.ViewCommonPopBinding
import com.feeyo.groundservice.checkin.model.CheckInTaskItemBO
import com.feeyo.groundservice.checkin.model.NodeBO
import com.feeyo.groundservice.checkin.viewmodel.CheckInViewModel
import com.feeyo.groundservice.composewidget.util.dimenToDp
import com.feeyo.groundservice.composewidget.util.dimenToSp
import com.feeyo.groundservice.composewidget.util.drawableToPainter
import com.feeyo.groundservice.composewidget.util.intervalClick
import com.feeyo.groundservice.composewidget.util.toComposeColor
import com.feeyo.groundservice.composewidget.view.tab.SwitchButton
import com.feeyo.groundservice.composewidget.view.util.HorizontalSpace
import com.feeyo.groundservice.composewidget.view.util.VerticalSpace
import com.lxj.xpopup.core.DrawerPopupView

/**
 *作者：70893 on 2025-09-05
 *描述：
 */
class CheckInDetailRightAttachPop(private val mContext: Context) : DrawerPopupView(mContext) {


    init {
        id = android.R.id.content
        setViewTreeLifecycleOwner(mContext as AppCompatActivity)
        setViewTreeSavedStateRegistryOwner(mContext)
    }


    private lateinit var binding: ViewCommonPopBinding

    override fun getImplLayoutId(): Int {
        return R.layout.view_common_pop
    }

    override fun onCreate() {
        super.onCreate()
        binding = ViewCommonPopBinding.bind(this.popupImplView)
        binding.popCp.apply {

            setContent {
                val statusBarHeight =
                    WindowInsets.statusBars.asPaddingValues().calculateTopPadding()
                val viewModel: CheckInViewModel = viewModel(mContext as AppCompatActivity)

                Box(
                    modifier = Modifier.fillMaxSize()
                        .padding(top = statusBarHeight)
                        .background(color = R.color.white.toComposeColor())
                        .padding(horizontal = R.dimen.d15.dimenToDp())
                ) {
                    Column(
                        modifier = Modifier.fillMaxSize()
                            .padding(
                                top = R.dimen.d20.dimenToDp(),
                                bottom = R.dimen.d60.dimenToDp()
                            )
                    ) {
                        //人员信息
                        PersonInfoAndStatus(
                            onUpdatePersonStatus = {
                                val uid = openDetailData.value?.user?.uid ?: ""
                                assert(uid.isNotEmpty()) {
                                    toastCenter("没有用户")
                                    return@PersonInfoAndStatus
                                }
                                viewModel.updateCheckInUserStatus(
                                    uid,
                                    if (it) 1 else 0,
                                    object : SuccessCallback {
                                        override fun success() {
                                            super.success()
                                            //更新本地数据，刷新主页标识
                                            openDetailData.value?.user?.enable?.value = it
                                        }
                                    })
                            }
                        )
                        //值机记录
                        CheckInRecord(
                            onNodeUpdate = {
                                viewModel.updateNode(
                                    it.id,
                                    it.updated_time,
                                    object : SuccessCallback {
                                        override fun success() {
                                            super.success()
                                            checkInListRefreshFlag.longValue =
                                                System.currentTimeMillis()
                                        }
                                    }
                                )
                            },
                            onDel = {
                                viewModel.delTask(it, object : SuccessCallback {
                                    override fun success() {
                                        super.success()
                                        checkInListRefreshFlag.longValue =
                                            System.currentTimeMillis()
                                    }
                                })
                            }
                        )
                    }

                    //人员可用才能新增值机
                    if (openDetailData.value?.user?.enable?.value == true){
                        //新增值机按钮
                        Box(
                            modifier = Modifier.fillMaxWidth().height(R.dimen.d44.dimenToDp())
                                .padding(bottom = R.dimen.d4.dimenToDp())
                                .background(
                                    color = R.color.white.toComposeColor(),
                                    shape = RoundedCornerShape(R.dimen.d5.dimenToDp())
                                )
                                .border(
                                    width = R.dimen.d1.dimenToDp(),
                                    color = statusBarColor.toComposeColor(),
                                    shape = RoundedCornerShape(R.dimen.d5.dimenToDp())
                                ).intervalClick {
                                    ActivityUtils.getTopActivity()
                                        ?.showAddCheckInPop(openDetailData.value!!.user)
                                }.align(Alignment.BottomCenter),
                            contentAlignment = Alignment.Center
                        ) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    painter = R.drawable.icon_add.drawableToPainter(),
                                    contentDescription = null,
                                    modifier = Modifier.size(R.dimen.d12.dimenToDp()),
                                    tint = statusBarColor.toComposeColor()
                                )
                                HorizontalSpace(R.dimen.d5.dimenToDp())
                                Text(
                                    text = "新增值机",
                                    fontSize = R.dimen.d16.dimenToSp(),
                                    fontWeight = FontWeight.W400,
                                    color = statusBarColor.toComposeColor()
                                )
                            }
                        }
                    }
                }

                DisposableEffect(Unit) {
                    onDispose {
                        openDetailData.value = null
                    }
                }

            }
        }
    }


    //人员信息
    @Composable
    private fun PersonInfoAndStatus(
        onUpdatePersonStatus: (Boolean) -> Unit
    ) {
        val open = remember { mutableStateOf(openDetailData.value?.user?.enable?.value ?: false) }
        //人员信息
        Column(
            modifier = Modifier.fillMaxWidth()
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                //姓名
                Text(
                    text = openDetailData.value?.user?.username.dealString(),
                    fontSize = R.dimen.d18.dimenToSp(),
                    fontWeight = FontWeight.W800,
                    color = R.color.black_27.toComposeColor()
                )

                SwitchButton(
                    open = open.value,
                    onSwitch = {
                        open.value = it
                        //更新可用状态
                        onUpdatePersonStatus(it)
                    },
                    bottomWidth = R.dimen.d72.dimenToDp(),
                    bottomHeight = R.dimen.d32.dimenToDp(),
                    padding = R.dimen.d4.dimenToDp(),
                    bottomOpenBgColor = R.color.green_07C160.toComposeColor(),
                    bottomCloseBgColor = R.color.gray_D4.toComposeColor(),
                    openText = "可用",
                    openTextSize = R.dimen.d16.dimenToSp(),
                    openTextColor = R.color.white.toComposeColor(),
                    closeText = "停用",
                    slideBarWidth = R.dimen.d24.dimenToDp(),//参考高度 这个值可以定义，主要修正滑块的默认计算宽度
                    closeTextSize = R.dimen.d16.dimenToSp(),
                    closeTextColor = R.color.black_66.toComposeColor(),
                )
            }
            VerticalSpace(R.dimen.d5.dimenToDp())
            //值机时长
            Text(
                text = "值机时长：${openDetailData.value?.task?.totalTime ?: "0分钟"}",
                fontSize = R.dimen.d12.dimenToSp(),
                fontWeight = FontWeight.W400,
                color = R.color.black_33.toComposeColor().copy(0.55f)
            )
            VerticalSpace(R.dimen.d5.dimenToDp())
            //值机次数
            Text(
                text = "值机次数：${openDetailData.value?.task?.checked_count ?: 0}",
                fontSize = R.dimen.d12.dimenToSp(),
                fontWeight = FontWeight.W400,
                color = R.color.black_33.toComposeColor().copy(0.55f)
            )
        }

    }

    //值机记录
    @Composable
    private fun CheckInRecord(
        onNodeUpdate: (node: NodeBO) -> Unit,
        onDel: (taskId: String) -> Unit
    ) {
        Text(
            text = "值机记录",
            fontSize = R.dimen.d15.dimenToSp(),
            fontWeight = FontWeight.W500,
            color = R.color.black_33.toComposeColor(),
            modifier = Modifier.padding(
                top = R.dimen.d20.dimenToDp(),
                bottom = R.dimen.d8.dimenToDp()
            )
        )

        //列表
        Column(
            modifier = Modifier.fillMaxWidth().verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(R.dimen.d12.dimenToDp())
        ) {
            val list = openDetailData.value?.task?.task_list ?: emptyList()
            list.sortedByDescending {
                //按照结束时间倒序
                it.task.endTime
            }.forEach {
                CheckInRecordItem(item = it, onNodeUpdate = onNodeUpdate, onDel = onDel)
            }
        }


    }

    @Composable
    private fun CheckInRecordItem(
        item: CheckInTaskItemBO,
        onNodeUpdate: (node: NodeBO) -> Unit,
        onDel: (taskId: String) -> Unit
    ) {
        var targetNode: NodeBO? = null//目标节点
        val txtColor = if (item.task.isEnd) {
            //已完成
            R.color.black_33.toComposeColor()
        } else if (item.task.isStart) {
            //进行中
            targetNode = item.endNode
            R.color.white.toComposeColor()
        } else {
            //未开始
            targetNode = item.startNode
            R.color.white.toComposeColor()
        }

        val bgColor = if (item.task.isEnd) {
            //已完成
            R.color.gray_D4.toComposeColor()
        } else if (item.task.isStart) {
            R.color.green_06B860.toComposeColor()
        } else {
            R.color.blue_2E76EE.toComposeColor()
        }


        Box(
            modifier = Modifier.fillMaxWidth()
                .background(
                    color = bgColor,
                    shape = RoundedCornerShape(R.dimen.d4.dimenToDp())
                ).padding(R.dimen.d12.dimenToDp())
        ) {
            Column(
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    text = "柜台：${item.focus_data.focus_info}",
                    fontSize = R.dimen.d14.dimenToSp(),
                    fontWeight = FontWeight.W400,
                    color = txtColor
                )
                VerticalSpace(R.dimen.d4.dimenToDp())
                val start = item.task.startTime.formatTimeHMWithDay()
                val end = item.task.endTime.formatTimeHMWithDay()
                Text(
                    text = "值机时间：$start-$end",
                    fontSize = R.dimen.d14.dimenToSp(),
                    fontWeight = FontWeight.W400,
                    color = txtColor
                )
                VerticalSpace(R.dimen.d4.dimenToDp())
                Text(
                    text = "调度员：${item.task.truename}",
                    fontSize = R.dimen.d14.dimenToSp(),
                    fontWeight = FontWeight.W400,
                    color = txtColor
                )

                //按钮
                if (item.task.isEnd) {

                } else if (item.task.isStart) {
                    VerticalSpace(R.dimen.d12.dimenToDp())
                    BtnView(title = "完成", txtColor = txtColor, onClick = {
                        targetNode?.let {
                            getConfirmDlg(
                                "", "确定完成任务吗?", R.color.black_33,
                                confirmListener = object : SuccessCallback {
                                    override fun success() {
                                        super.success()
                                        onNodeUpdate(it)
                                    }
                                })?.show()
                        } ?: toastCenter("没有完成节点")
                    })

                } else {
                    VerticalSpace(R.dimen.d12.dimenToDp())
                    Row {
                        BtnView(title = "开始", txtColor = txtColor, onClick = {
                            targetNode?.let {
                                getConfirmDlg(
                                    "", "确定开始任务吗?", R.color.black_33,
                                    confirmListener = object : SuccessCallback {
                                        override fun success() {
                                            super.success()
                                            onNodeUpdate(it)
                                        }
                                    })?.show()
                            } ?: toastCenter("没有开始节点")
                        })
                        HorizontalSpace(R.dimen.d16.dimenToDp())
                        BtnView(title = "删除", txtColor = txtColor, onClick = {
                            getConfirmDlg(
                                "", "确定删除任务吗?", R.color.red_EB5451,
                                confirmListener = object : SuccessCallback {
                                    override fun success() {
                                        super.success()
                                        onDel(item.task.id)
                                    }
                                })?.show()
                        }
                        )
                    }
                }
            }
        }
    }

    @Composable
    private fun BtnView(
        title: String,
        txtColor: Color,
        onClick: () -> Unit
    ) {
        Box(
            modifier = Modifier.size(R.dimen.d60.dimenToDp(), R.dimen.d26.dimenToDp())
                .border(
                    width = R.dimen.d1.dimenToDp(),
                    color = txtColor,
                    shape = RoundedCornerShape(R.dimen.d4.dimenToDp())
                ).intervalClick {
                    onClick()
                },
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = title,
                fontSize = R.dimen.d14.dimenToSp(),
                fontWeight = FontWeight.W400,
                color = txtColor
            )
        }
    }

    override fun getPopupWidth(): Int {
        return (ScreenUtils.getAppScreenWidth() * 0.63f).toInt()
    }
}